from interface.widget import Page, scale
from tkinter import ttk
from utils.network import request, RespondError
from tkinter import messagebox


class RegisterPage(Page):

    def content(self, master):
        form_box = ttk.Frame(master)
        form_box.place(**scale(relx=0.5, rely=0.5, width=400, height=260, anchor='center'))

        account_label = ttk.Label(form_box, text='新账号')
        account_label.place(**scale(x=0, y=0, width=100, height=40))

        account_entry = ttk.Entry(form_box)
        account_entry.place(**scale(x=100, y=0, width=300, height=40))

        username_label = ttk.Label(form_box, text='用户名')
        username_label.place(**scale(x=0, y=60, width=100, height=40))

        username_entry = ttk.Entry(form_box)
        username_entry.place(**scale(x=100, y=60, width=300, height=40))

        password_label = ttk.Label(form_box, text='密码')
        password_label.place(**scale(x=0, y=120, width=100, height=40))

        password_entry = ttk.Entry(form_box, show='*')
        password_entry.place(**scale(x=100, y=120, width=300, height=40))

        def switch_to_login_page():
            from interface.pages.login import LoginPage
            self.master.close_page()
            self.master.open_page(LoginPage(self.master))

        button = ttk.Button(form_box, text='登录', command=switch_to_login_page)
        button.place(**scale(x=0, y=210, width=100, height=50))

        def register_button_method():
            try:
                res = request('/user/register', {
                    'account': account_entry.get(),
                    'password': password_entry.get(),
                    'username': username_entry.get()
                })
                messagebox.showinfo(title='注册成功',
                                    message='账号：{}\n用户名{}'.format(res['account'], res['username']))
                switch_to_login_page()
            except RespondError as e:
                messagebox.showerror('Error', e.res)

        button = ttk.Button(form_box, text='注册', command=register_button_method)
        button.place(**scale(x=120, y=210, width=280, height=50))
